package com.tinem.platform.web.auth.login.oauth2.ad;

import cn.hutool.core.util.StrUtil;
import com.tinem.platform.module.pojo.enums.rbac.LoginType;
import com.tinem.platform.module.starter.jpa.repository.rbac.RbacAuthoritiesGroupUserRepository;
import com.tinem.platform.module.starter.jpa.repository.rbac.RbacUserRepository;
import com.tinem.platform.web.auth.login.LoginService;
import com.tinem.platform.web.auth.login.oauth2.Oauth2Server;
import com.tinem.platform.web.auth.page.LoginUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Map;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className GlpOauthUserServiceImpl
 * @description TODO
 * @site 
 * @company 
 * @create 2020-08-24 17:08
 */
@Service("oauthUserService")
public class OauthUserServiceImpl extends DefaultOAuth2UserService {

    @Autowired
    Map<String,Oauth2Server> mapOauth2Server;

    @Resource
    RbacUserRepository rbacUserRepository;

    @Resource
    LoginService loginService;

    @Resource
    RbacAuthoritiesGroupUserRepository rbacAuthoritiesGroupUserRepository;


    @Override
    @Transactional(rollbackOn = Exception.class)
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {

        OAuth2User oAuth2User = super.loadUser(userRequest);

        String clientId = userRequest.getClientRegistration().getRegistrationId();
        Oauth2Server oauth2Server = mapOauth2Server.get(StrUtil.format("oauth2Server-{}",clientId));

        //获取用户id
        String oid = oauth2Server.getOpenId(oAuth2User);

        String userId = oauth2Server.findUserByOpenId(oid);
        if(userId == null){
            userId = loginService.bindUser(oauth2Server,oAuth2User);
        }
        LoginUserInfo loginUserInfo = loginService.getLoginUser(userId);
        loginUserInfo.setLoginType(LoginType.OATUH2_AZURE);
        loginUserInfo.setOAuth2User(oAuth2User);

        //记录用户登录信息
        oauth2Server.saveInfo(loginUserInfo);

        return loginUserInfo;
    }
}
